<template>
  <div>
    <!--搜索与重置功能    -->
    <div class="search">
      <el-input placeholder="请输入班级名称" style="width: 200px" v-model="className"></el-input>
      <el-button type="info" plain style="margin-left: 10px" @click="load(1)">查询</el-button>
      <el-button type="warning" plain style="margin-left: 10px" @click="reset">重置</el-button>
    </div>

    <div class="operation">
      <el-button type="primary" plain @click="handleAdd">新增</el-button>
      <el-button type="danger" plain @click="delBatch">批量删除</el-button>
    </div>

    <div class="table">
      <el-table :data="tableData" stripe @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center"></el-table-column>
        <el-table-column prop="id" label="序号" width="80" align="center" sortable></el-table-column>
        <el-table-column prop="img" label="班级封面" show-overflow-tooltip>
          <template v-slot="scope">
            <div style="display: flex; align-items: center">
              <el-image style="width: 60px; height: 40px; border-radius: 10px" v-if="scope.row.img" :src="scope.row.img" :preview-src-list="[scope.row.img]"></el-image>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="className" label="班级名称" show-overflow-tooltip></el-table-column>
        <el-table-column prop="PlanId" label="课程计划" show-overflow-tooltip>
          <template v-slot="scope">
            <el-button type="success" size="mini" @click="viewDataInit(scope.row, 'plan')">查看</el-button>
          </template>
        </el-table-column>
        <el-table-column prop="announcement" label="班级介绍" show-overflow-tooltip width="300px"></el-table-column>

        <el-table-column prop="members" label="班级成员" show-overflow-tooltip>
          <template v-slot="scope">
            <el-button type="warning" size="mini" @click="viewDataInit(scope.row, 'management')">点击管理</el-button>
          </template>
        </el-table-column>
        <el-table-column prop="evaluationPaper" label="评测试卷" show-overflow-tooltip>
          <template v-slot="scope">
            <el-button type="success" size="mini" @click="viewDataInit(scope.row, 'test')">点击上传</el-button>
          </template>
        </el-table-column>


        <el-table-column label="操作" width="180" align="center">
          <template v-slot="scope">
            <el-button plain type="primary" @click="handleEdit(scope.row)" size="mini">编辑</el-button>
            <el-button plain type="danger" size="mini" @click="del(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination
            background
            @current-change="handleCurrentChange"
            :current-page="pageNum"
            :page-sizes="[5, 10, 20]"
            :page-size="pageSize"
            layout="total, prev, pager, next"
            :total="total">
        </el-pagination>
      </div>
    </div>
<!--弹窗，添加班级-->
    <el-dialog title="班级信息" :visible.sync="fromVisible" width="55%" :close-on-click-modal="false" destroy-on-close>
      <el-form label-width="100px" style="padding-right: 50px" :model="form" :rules="rules" ref="formRef">
        <el-form-item label="班级封面">
          <el-upload class="avatar-uploader" :action="$baseUrl + '/files/upload'" :headers="{ token: user.token }" list-type="picture" :on-success="handleImgSuccess">
            <el-button type="primary">上传图片</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item prop="className" label="班级名称">
          <el-input v-model="form.className" autocomplete="off" placeholder="请输入班级名称"></el-input>
        </el-form-item>
        <el-form-item prop="announcement" label="班级介绍">
          <div id="editor"></div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="fromVisible = false">取 消</el-button>
        <el-button type="primary" @click="save">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 弹窗：评测试卷 -->
    <el-dialog title="评测试卷" :visible.sync="handleTest" width="50%" :close-on-click-modal="false" destroy-on-close>
      <el-form :model="testForm" :rules="testRules" ref="testFormRef" label-width="100px">
        <el-form-item prop="examName" label="评测名称">
          <el-input v-model="testForm.examName" autocomplete="off" placeholder="请输入评测名称"></el-input>
        </el-form-item>
        <el-form-item prop="examFile" label="评测内容">
          <el-upload class="avatar-uploader" :action="$baseUrl + '/files/upload'" :headers="{ token: user.token }" :on-success="handleTestFileSuccess" list-type="picture">
            <el-button type="primary">上传文件</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item prop="examTime" label="评测时间">
          <el-date-picker v-model="testForm.examTime" type="datetime" placeholder="选择评测时间"></el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleTest = false">取 消</el-button>
        <el-button type="primary" @click="saveTest">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 弹窗：课程计划 -->
    <el-dialog title="课程计划" :visible.sync="handleClassPlan" width="50%" :close-on-click-modal="false" destroy-on-close>

        <div class="operation">
          <el-button type="primary" plain @click="addplan()">新增教学计划</el-button>
          <el-button type="danger" plain @click="delBatchplan">批量删除</el-button>
        </div>

        <div class="table">
          <el-table :data="plantableData" stripe @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" align="center"></el-table-column>
            <el-table-column prop="id" label="序号" width="80" align="center" sortable></el-table-column>
            <el-table-column prop="planName" label="计划名称" show-overflow-tooltip></el-table-column>
            <el-table-column prop="planTime" label="计划时间" show-overflow-tooltip></el-table-column>
            <el-table-column prop="planContent" label="计划内容" show-overflow-tooltip></el-table-column>


            <el-table-column label="操作" width="180" align="center">
              <template v-slot="scope">
                <el-button plain type="primary" @click="handleEditplan(scope.row)" size="mini">编辑</el-button>
                <el-button plain type="danger" size="mini" @click="delplan(scope.row.id)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>

          <div class="pagination">
            <el-pagination
                background
                @current-change="handleCurrentChange"
                :current-page="pageNum"
                :page-sizes="[5, 10, 20]"
                :page-size="pageSize"
                layout="total, prev, pager, next"
                :total="total">
            </el-pagination>
          </div>
        </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleClassPlan = false">取 消</el-button>
        <el-button type="primary" @click="handleClassPlan = false">确 定</el-button>
      </div>
    </el-dialog>
<!--弹窗：添加计划-->
    <el-dialog title="课程计划" :visible.sync="handleClassPlanAdd" width="50%" :close-on-click-modal="false" destroy-on-close>

        <el-form :model="planForm" :rules="planRules" ref="planFormRef" label-width="100px">
          <el-form-item prop="planName" label="计划名称">
            <el-input v-model="planForm.planName" autocomplete="off" placeholder="请输入计划名称"></el-input>
          </el-form-item>
          <el-form-item prop="planContent" label="计划内容">
            <el-input v-model="planForm.planContent" autocomplete="off" placeholder="请输入计划内容"></el-input>
          </el-form-item>
          <el-form-item prop="planTime" label="计划时间">
            <el-date-picker v-model="planForm.planTime" type="datetime" placeholder="选择计划时间"></el-date-picker>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="handleClassPlanAdd = false">取 消</el-button>
          <el-button type="primary" @click="savePlan">确 定</el-button>
        </div>
      </el-dialog>

    <!-- 弹窗：课堂成员管理 -->
    <el-dialog :title="'课堂成员管理 共有(' + membersData.length + ' 个学生)'" :visible.sync="editorVisible" width="50%" :close-on-click-modal="false" destroy-on-close>
      <el-table :data="membersData" v-if="membersData.length">
        <el-table-column prop="id" label="序号"></el-table-column>
        <el-table-column prop="avatar" label="头像" width="80">
          <template v-slot="scope">
            <el-image :src="scope.row.avatar" style="width: 60px; height: 60px; border-radius: 50%"></el-image>
          </template>
        </el-table-column>
        <el-table-column prop="name" label="姓名"></el-table-column>
        <el-table-column prop="phone" label="电话"></el-table-column>
        <el-table-column prop="email" label="邮箱"></el-table-column>

        <el-table-column label="操作" width="100">
          <template v-slot="scope">
            <el-button plain type="danger" @click="deleteMember(scope.row.id)" size="mini">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div v-else style="text-align: center; color: #999; margin: 20px;">班级暂无成员</div>

    </el-dialog>
  </div>
</template>

<script>
import E from 'wangeditor'

export default {
  name: "Class",/*组件名为“Class”*/
  data() {
    return {
      editor: null,/*富文本编辑器*/
      test: null,
      tableData: [],
      plantableData:[],
      pageNum: 1,
      pageSize: 10,
      total: 0,
      className: null,
      planpageNum: 1,
      planpageSize: 10,
      plantotal: 0,

      planName: null,
      recommend: null,
      fromVisible: false,
      editorVisible: false,
      handleClassPlan: false,
      handleClassPlanAdd:false,
      planVisible: false,
      handleTest: false,
      form: {},
      user: JSON.parse(localStorage.getItem('xm-user') || '{}'),
      rules: {
        className: [
          {required: true, message: '请输入课程名称', trigger: 'blur'},
        ],
        price: [
          {required: true, message: '请输入课程价格', trigger: 'blur'},
        ],
      },
      testForm: {},

      planForm: {},
      membersData: [],
      ids: [],
      number: []

    }
  },
  created() {
    this.load(1)
  },
  methods: {
    /*新增班级的，初始化富文本编辑器，如果有公告就展示在里面*/
    initWangEditor(announcement) {
      this.$nextTick(() => {
        this.editor = new E('#editor')
        this.editor.config.placeholder = '请输入内容'
        this.editor.config.uploadFileName = 'file'
        this.editor.config.uploadImgServer = 'http://localhost:9090/files/wang/upload'
        this.editor.create()
        setTimeout(() => {
          this.editor.txt.html(announcement)
        })
      })
    },
  addplan(){
      this.handleClassPlanAdd=true
  },

    /*根据类型初始化页面数据展示,点击*/
    viewDataInit(data, type) {
      this.viewData = data
      if (type === 'plan') {
        this.handleClassPlan = true
        this.loadplan(this.viewData.id)
      } else if (type === 'management') {
        this.editorVisible = true
        this.loadMembers(this.viewData.id)
      } else if (type === 'test') {
        this.handleTest = true
      } else if(type==='planadd')
      {
        this.handleClassPlanAdd=true
      }
    },
    /*新增课程*/
    handleAdd() {
      this.form = {}
      this.fromVisible = true
      this.initWangEditor('')
    },

    handleEdit(row) {
      this.form = JSON.parse(JSON.stringify(row))
      this.fromVisible = true
      this.initWangEditor(this.form.announcement || '')
    },
    handleEditplan(row) {
      this.planForm = JSON.parse(JSON.stringify(row))
      this.handleClassPlanAdd=true

    },
    /*保存班级信息，判断是新增还是编辑*/
    save() {
      this.$refs.formRef.validate((valid) => {
        if (valid) {
          this.form.announcement = this.editor.txt.html()
          this.form.teacherId=this.user.id
          this.$request({
            url: this.form.id ? '/classes/update' : '/classes/add',
            method: this.form.id ? 'PUT' : 'POST',
            data: this.form
          }).then(res => {
            if (res.code === '200') {
              console.log(res.data)
              this.$message.success('保存成功')
              this.load(1)
              this.fromVisible = false
            } else {
              this.$message.error(res.msg)
            }
          })
        }
      })
    },
    /*删除指定ID班级*/
    del(id) {
      this.$confirm('您确定删除吗？', '确认删除', {type: "warning"}).then(response => {

        this.$request.delete('/classes/delete/' + id).then(res => {
          if (res.code === '200') {
            this.$message.success('操作成功')
            this.load(1)
          } else {
            this.$message.error(res.msg)
          }
        })
      }).catch(() => {
      })
    },
    /*删除指定ID计划*/
    delplan(id) {
      this.$confirm('您确定删除吗？', '确认删除', {type: "warning"}).then(response => {
        this.$request.delete('/plan/delete/' + id).then(res => {
          if (res.code === '200') {
            this.$message.success('操作成功')
            this.loadplan(this.viewData.id)
          } else {
            this.$message.error(res.msg)
          }
        })
      }).catch(() => {
      })
    },
    /*处理表格中行选择*/
    handleSelectionChange(rows) {
      this.ids = rows.map(v => v.id)
    },
    /*批量删除*/
    delBatch() {
      if (!this.ids.length) {
        this.$message.warning('请选择数据')
        return
      }
      this.$confirm('您确定批量删除吗？', '确认删除', {type: "warning"}).then(response => {
        this.$request.delete('/classes/delete/batch', {data: this.ids}).then(res => {
          if (res.code === '200') {
            this.$message.success('操作成功')
            this.load(1)
          } else {
            this.$message.error(res.msg)
          }
        })
      }).catch(() => {
      })
    },
    /*批量删除*/
    delBatchplan() {
      if (!this.ids.length) {
        this.$message.warning('请选择数据')
        return
      }
      this.$confirm('您确定批量删除吗？', '确认删除', {type: "warning"}).then(response => {
        this.$request.delete('/plan/delete/batch', {data: this.ids}).then(res => {
          if (res.code === '200') {
            this.$message.success('操作成功')
            this.loadplan(this.viewData.id)
          } else {
            this.$message.error(res.msg)
          }
        })
      }).catch(() => {
      })
    },
    /*查询*/
    load(pageNum) {
      if (pageNum) this.pageNum = pageNum
      this.$request.get('/classes/selectPage', {
        params: {
          pageNum: this.pageNum,
          pageSize: this.pageSize,
          className: this.className,
        }
      }).then(res => {
        this.tableData = res.data?.list
        this.total = res.data?.total
        console.log(res.data)
      })
    },
    /*查询计划*/
    loadplan(classId) {
      this.$request.get('/plan/selectByClassId/'+classId, ).then(res => {
        this.plantableData = res.data
        this.plantotal = res.data?.total
        console.log(res.data)
      })
    },
    reset() {
      this.name = null
      this.recommend = null
      this.load(1)
    },
    /*点击分页，用load重新加载页码的页面*/
    handleCurrentChange(pageNum) {
      this.load(pageNum)
    },
    /*处理图片上传成功*/
    handleImgSuccess(res) {
      this.form.img = res.data
    },
    /*处理试卷上传成功*/
    handleTestFileSuccess(res) {
      this.testForm.examFile = res.data
    },
    /*测评试卷的上传*/
    saveTest() {
      this.$refs.testFormRef.validate((valid) => {
        this.testForm.classId=this.viewData.id
        if (valid) {
          this.$request({
            url: this.testForm.id ? '/exam/update' : '/exam/add',
            method: this.testForm.id ? 'PUT' : 'POST',
            data: this.testForm
          }).then(res => {
            if (res.code === '200') {
              this.$message.success('保存成功')
              this.handleTest=false
              this.testForm={}
            } else {
              this.$message.error(res.msg)
            }
          })
        }
      })
    },
    /*保存计划*/
    savePlan() {

      this.$refs.planFormRef.validate((valid) => {
        this.planForm.classId=this.viewData.id
        if (valid) {
          this.$request({
            url: this.planForm.id ? '/plan/update' : '/plan/add',
            method: this.planForm.id ? 'PUT' : 'POST',
            data: this.planForm
          }).then(res => {
            if (res.code === '200') {
              this.$message.success('保存成功')
              this.loadplan(this.viewData.id)
              this.handleClassPlanAdd = false
              this.planForm={}
            } else {
              this.$message.error(res.msg)
            }
          })
        }
      })
    },
    loadMembers(classId) {
      this.$request.get('/student/selectByClassId/'+classId).then(res => {
        if (res.code === '200') {
          this.membersData = res.data || []
        } else {
          this.$message.error(res.msg)
        }
      })
    },

    editMember(row) {
      // Implement edit member functionality
    },

    deleteMember(id) {
      this.$confirm('您确定删除吗？', '确认删除', {type: "warning"}).then(response => {
        this.$request.delete('/student/delete/' + id).then(res => {
          if (res.code === '200') {
            this.$message.success('操作成功')

            this.loadMembers(this.viewData.id)
          } else {
            this.$message.error(res.msg)
          }
        })
      }).catch(() => {
      })
    },
    handleEditMemberImgSuccess(res, file, fileList) {
      // Implement handle image upload success
    }

  }
}
</script>

<style scoped>
</style>
